package web.Users;

import domain.Users;
import org.apache.commons.beanutils.BeanUtils;
import service.User_Service;
import service.impl.User_ServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置页面编码
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();
/*        //获取验证码
        String verifycode = request.getParameter("verifycode");
        String code =(String) session.getAttribute("code");
        if (!code.equalsIgnoreCase(verifycode))
        {
           //验证码错误
            request.setAttribute("addError","验证码错误");
            request.getRequestDispatcher("/users/register.jsp").forward(request,response);
            return;
        }*/



        //获取Map集合
        Map<String,String[]> map = request.getParameterMap();
        //封装Users对象
        Users users = new Users();
        try {
            BeanUtils.populate(users,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


        //调用UserServer添加
        User_Service user_service = new User_ServiceImpl();

        int req =  user_service.addUser(users);

        switch (req){
            case 1:
                request.setAttribute("success","添加成功");
                break;
            case 0:
                request.setAttribute("addError","添加失败");
                break;
            case -1:
                request.setAttribute("addError","用户已存在");
                break;
        }
        request.getRequestDispatcher("/users/register.jsp").forward(request,response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
